package com.lty.jeeg.server.modules.fas.service.impl;

import com.lty.jeeg.server.common.utils.BeanConverter;
import com.lty.jeeg.server.modules.fas.dto.GoodsCategoryDTO;
import com.lty.jeeg.server.modules.fas.model.GoodsCategory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lty.jeeg.server.modules.fas.dao.GoodsCategoryDao;
import com.lty.jeeg.server.modules.fas.service.GoodsCategoryService;

import java.util.List;

/**
 * @author : LTY
 * @date : 2019-01-18 09:17:16
 * Description : 商品分类
 */
@Service
@Slf4j
public class GoodsCategoryServiceImpl implements GoodsCategoryService {

    private final GoodsCategoryDao goodsCategoryDao;

    @Autowired
    public GoodsCategoryServiceImpl(GoodsCategoryDao goodsCategoryDao) {
        this.goodsCategoryDao = goodsCategoryDao;
    }

    @Override
    public GoodsCategoryDTO getById(Long id) {
        return goodsCategoryDao.getById(id);
    }

    @Override
    public GoodsCategoryDTO getParentById(Long id) {
        return goodsCategoryDao.getById(id);
    }

    @Override
	@Transactional(rollbackFor = Exception.class)
	public int delete(Long id) {
		log.debug("删除GoodsCategory=>{}", id);
		return goodsCategoryDao.delete(id);
	}

    @Override
	@Transactional(rollbackFor = Exception.class)
	public int update(GoodsCategoryDTO categoryDTO) {
        Long parentId = categoryDTO.getParentId();
        if (parentId == 0) {
            categoryDTO.setParentIds("0,");
        } else {
            GoodsCategoryDTO parent = goodsCategoryDao.getById(parentId);
            categoryDTO.setParentIds(parent.getParentIds() + parent.getId() + ",");
        }

        categoryDTO.preUpdate();
        GoodsCategory goodsCategory = BeanConverter.map(categoryDTO, GoodsCategory.class);
        int update = goodsCategoryDao.update(goodsCategory);
        log.debug("修改GoodsCategory=>{}", goodsCategory.getId());
        return update;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long save(GoodsCategoryDTO categoryDTO) {
        Long parentId = categoryDTO.getParentId();
        if (parentId == 0) {
            categoryDTO.setParentIds("0,");
        } else {
            GoodsCategoryDTO parent = goodsCategoryDao.getById(parentId);
            categoryDTO.setParentIds(parent.getParentIds() + parent.getId() + ",");
        }

        categoryDTO.preInsert();

        Long id = goodsCategoryDao.save(BeanConverter.map(categoryDTO, GoodsCategory.class));
        log.debug("新增GoodsCategory=>{}", id);
        return id;
    }

    @Override
    public List<GoodsCategoryDTO> treeList() {
        return goodsCategoryDao.treeList();
    }

    @Override
    public List<GoodsCategoryDTO> listAll() {
        return goodsCategoryDao.listAll();
    }



}
